home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / APPLICATION.PY < prev    next >
Encoding:
Python Source  |  2000-09-07  |  21.1 KB  |  562 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. __doc__='''Application support
  65.  
  66.  
  67. $Id: Application.py,v 1.128.2.5 2000/09/07 16:06:26 brian Exp $'''
  68. __version__='$Revision: 1.128.2.5 $'[11:-2]
  69.  
  70. import Globals,Folder,os,sys,App.Product, App.ProductRegistry, misc_
  71. import time, traceback, os, string, Products
  72. from string import strip, lower, find, rfind, join
  73. from DateTime import DateTime
  74. from AccessControl.User import UserFolder
  75. from App.ApplicationManager import ApplicationManager
  76. from webdav.NullResource import NullResource
  77. from FindSupport import FindSupport
  78. from urllib import quote
  79. from cStringIO import StringIO
  80. from AccessControl.PermissionRole import PermissionRole
  81. from App.ProductContext import ProductContext
  82. from misc_ import Misc_
  83. import ZDOM
  84. from zLOG import LOG, ERROR
  85. from HelpSys.HelpSys import HelpSys
  86.  
  87.  
  88. _standard_error_msg='''\
  89. <dtml-var standard_html_header>
  90.  
  91. <dtml-if error_message>
  92.  <dtml-var error_message>
  93. <dtml-else>
  94.  
  95. <TABLE BORDER="0" WIDTH="100%">
  96. <TR VALIGN="TOP">
  97.  
  98. <TD WIDTH="10%" ALIGN="CENTER">
  99. <IMG SRC="<dtml-var BASE1>/p_/ZButton" ALT="Zope">
  100. </TD>
  101.  
  102. <TD WIDTH="90%">
  103.   <H2>Zope Error</H2>
  104.   <P>Zope has encountered an error while publishing this resource.
  105.   </P>
  106.   
  107.   <P>
  108.   <STRONG>Error Type: <dtml-var error_type html_quote></STRONG><BR>
  109.   <STRONG>Error Value: <dtml-var error_value html_quote></STRONG><BR> 
  110.   </P>
  111.  
  112.   <HR NOSHADE>
  113.  
  114.   <P>Troubleshooting Suggestions</P>
  115.  
  116.   <UL>
  117.   <dtml-if "error_type in ('KeyError','NameError')">
  118.   <LI>This resource may be trying to reference a
  119.   nonexistent object or variable <STRONG><dtml-var error_value></STRONG>.</LI>
  120.   </dtml-if>
  121.   <LI>The URL may be incorrect.</LI>
  122.   <LI>The parameters passed to this resource may be incorrect.</LI>
  123.   <LI>A resource that this resource relies on may be encountering an error.</LI>
  124.   </UL>
  125.  
  126.   <P>For more detailed information about the error, please
  127.   refer to the HTML source for this page.
  128.   </P>
  129.  
  130.   <P>If the error persists please contact the site maintainer.
  131.   Thank you for your patience.
  132.   </P>
  133. </TD></TR>
  134. </TABLE>
  135.  
  136. <dtml-comment>
  137.  Here, events like logging and other actions may also be performed, such as
  138.  sending mail automatically to the administrator.
  139. </dtml-comment>
  140.  
  141. </dtml-if>
  142. <dtml-var standard_html_footer>'''
  143.  
  144.  
  145. class Application(Globals.ApplicationDefaultPermissions,
  146.                   ZDOM.Root, Folder.Folder,
  147.                   App.ProductRegistry.ProductRegistry, FindSupport):
  148.     """Top-level system object"""
  149.     title    ='Zope'
  150.     #__roles__=['Manager', 'Anonymous']
  151.     __defined_roles__=('Manager','Anonymous','Owner')
  152.     web__form__method='GET'
  153.     isTopLevelPrincipiaApplicationObject=1
  154.     _isBeingUsedAsAMethod_=0
  155.  
  156.     # Create the help system object
  157.     HelpSys=HelpSys('HelpSys')
  158.  
  159.     p_=misc_.p_
  160.     misc_=misc_.misc_
  161.  
  162.     _reserved_names=('standard_html_header',
  163.                      'standard_html_footer',
  164.                      'standard_error_message',
  165.                      'Control_Panel')
  166.  
  167.     # This class-default __allow_groups__ ensures that the
  168.     # superuser can still access the system if the top-level
  169.     # UserFolder is deleted. This is necessary to allow people
  170.     # to replace the top-level UserFolder object.
  171.     
  172.     __allow_groups__=UserFolder()
  173.  
  174.     def title_and_id(self): return self.title
  175.     def title_or_id(self): return self.title
  176.  
  177.     def __init__(self):
  178.         # Initialize users
  179.         uf=UserFolder()
  180.         self.__allow_groups__=uf
  181.         self._setObject('acl_users', uf)
  182.  
  183.         # Initialize control panel
  184.         cpl=ApplicationManager()
  185.         cpl._init()
  186.         self._setObject('Control_Panel', cpl)
  187.  
  188.         # Note that this may happen before products are
  189.         # installed, so we have to use addDocument as stand-alone.
  190.         import Document
  191.         Document.manage_addDocument(
  192.             self,
  193.             'standard_html_header',
  194.             'Standard Html Header',
  195.             '<HTML><HEAD><TITLE><dtml-var title_or_id>' \
  196.             '</TITLE></HEAD><BODY BGCOLOR="#FFFFFF">')
  197.         Document.manage_addDocument(
  198.             self,
  199.             'standard_html_footer',
  200.             'Standard Html Footer',
  201.             '</BODY></HTML>')
  202.         Document.manage_addDocument(
  203.             self,
  204.             'standard_error_message',
  205.             'Standard Error Message',
  206.             _standard_error_msg)
  207.  
  208.     def id(self):
  209.         try:    return self.REQUEST['SCRIPT_NAME'][1:]
  210.         except: return self.title
  211.  
  212.     def __class_init__(self): Globals.default__class_init__(self)
  213.  
  214.     def PrincipiaRedirect(self,destination,URL1):
  215.         """Utility function to allow user-controlled redirects"""
  216.         if find(destination,'//') >= 0: raise 'Redirect', destination
  217.         raise 'Redirect', ("%s/%s" % (URL1, destination))
  218.     Redirect=ZopeRedirect=PrincipiaRedirect
  219.  
  220.     def __bobo_traverse__(self, REQUEST, name=None):
  221.  
  222.         try: return getattr(self, name)
  223.         except AttributeError: pass
  224.         try: return self[name]
  225.         except KeyError: pass
  226.         method=REQUEST.get('REQUEST_METHOD', 'GET')
  227.         if not method in ('GET', 'POST'):
  228.             return NullResource(self, name, REQUEST).__of__(self)
  229.  
  230.         REQUEST.RESPONSE.notFoundError("%s\n%s" % (name, method))
  231.  
  232.     def PrincipiaTime(self, *args):
  233.         """Utility function to return current date/time"""
  234.         return apply(DateTime, args)
  235.     ZopeTime=PrincipiaTime
  236.  
  237.     ZopeAttributionButton__roles__=None
  238.     def ZopeAttributionButton(self):
  239.         """Returns an HTML fragment that displays the 'powered by zope'
  240.         button along with a link to the Zope site."""
  241.         return '<a href="http://www.zope.org/Credits" target="_top"><img ' \
  242.                'src="%s/p_/ZopeButton" width="115" height="50" ' \
  243.                'border="0" alt="Powered by Zope"></a>' % self.REQUEST.BASE1
  244.  
  245.  
  246.     def DELETE(self, REQUEST, RESPONSE):
  247.         """Delete a resource object."""
  248.         self.dav__init(REQUEST, RESPONSE)
  249.         raise 'Forbidden', 'This resource cannot be deleted.'
  250.  
  251.     def MOVE(self, REQUEST, RESPONSE):
  252.         """Move a resource to a new location."""
  253.         self.dav__init(REQUEST, RESPONSE)
  254.         raise 'Forbidden', 'This resource cannot be moved.'
  255.     
  256.     test_url___allow_groups__=None
  257.     test_url=ZopeAttributionButton
  258.  
  259.     def absolute_url(self, relative=0):
  260.         """Return an absolute url to the object. Note that the url
  261.         will reflect the acquisition path of the object if the object
  262.         has been acquired."""
  263.         if relative: return ''
  264.         return self.aq_acquire('REQUEST')['BASE1']
  265.  
  266.     def getPhysicalPath(self):
  267.         '''Returns a path that can be used to access this object again
  268.         later, for example in a copy/paste operation.  Designed to
  269.         be used with getPhysicalRoot().
  270.         '''
  271.         # We're at the base of the path.
  272.         return ('',)
  273.  
  274.     def getPhysicalRoot(self): return self
  275.  
  276. class Expired(Globals.Persistent):
  277.     icon='p_/broken'
  278.  
  279.     def __setstate__(self, s={}):
  280.         dict=self.__dict__
  281.         if s.has_key('id'):
  282.             dict['id']=s['id']
  283.         elif s.has_key('__name__'):
  284.             dict['id']=s['__name__']
  285.         else: dict['id']='Unknown'
  286.         dict['title']='** Expired **'
  287.  
  288.     def __save__(self):
  289.         pass
  290.  
  291.     __inform_commit__=__save__
  292.  
  293. def initialize(app):
  294.     # Initialize the application
  295.  
  296.     # Initialize the cache:
  297.     app.Control_Panel.initialize_cache()
  298.  
  299.     # The following items marked b/c are backward compatibility hacks
  300.     # which make sure that expected system objects are added to the
  301.     # bobobase. This is required because the bobobase in use may pre-
  302.     # date the introduction of certain system objects such as those
  303.     # which provide Lever support.
  304.  
  305.     # b/c: Ensure that Control Panel exists.
  306.     if not hasattr(app, 'Control_Panel'):
  307.         cpl=ApplicationManager()
  308.         cpl._init()
  309.         app._setObject('Control_Panel', cpl)
  310.         get_transaction().note('Added Control_Panel')
  311.         get_transaction().commit()
  312.  
  313.     # b/c: Ensure that a ProductFolder exists.
  314.     if not hasattr(app.Control_Panel.aq_base, 'Products'):
  315.         app.Control_Panel.Products=App.Product.ProductFolder()
  316.         get_transaction().note('Added Control_Panel.Products')
  317.         get_transaction().commit()
  318.  
  319.     # b/c: Ensure that std err msg exists.
  320.     if not hasattr(app, 'standard_error_message'):
  321.         import Document
  322.         Document.manage_addDocument(
  323.             app,
  324.             'standard_error_message',
  325.             'Standard Error Message',
  326.             _standard_error_msg)
  327.         get_transaction().note('Added standard_error_message')
  328.         get_transaction().commit()
  329.  
  330.     # b/c: Ensure that Owner role exists.
  331.     if hasattr(app, '__ac_roles__') and not ('Owner' in app.__ac_roles__):
  332.         app.__ac_roles__=app.__ac_roles__ + ('Owner',)
  333.         get_transaction().note('Added Owner role')
  334.         get_transaction().commit()
  335.  
  336.     # Make sure we have Globals
  337.     root=app._p_jar.root()
  338.     if not root.has_key('ZGlobals'):
  339.         import BTree
  340.         app._p_jar.root()['ZGlobals']=BTree.BTree()
  341.         get_transaction().note('Added Globals')
  342.         get_transaction().commit()
  343.  
  344.     install_products(app)
  345.  
  346. def import_products(_st=type('')):
  347.     # Try to import each product, checking for and catching errors.
  348.     path_join=os.path.join
  349.     isdir=os.path.isdir
  350.     exists=os.path.exists
  351.     DictType=type({})
  352.     global_dict=globals()
  353.     silly=('__doc__',)
  354.     modules=sys.modules
  355.     have_module=modules.has_key
  356.     done={}
  357.  
  358.     for product_dir in Products.__path__:
  359.  
  360.         product_names=os.listdir(product_dir)
  361.         product_names.sort()
  362.  
  363.         for product_name in product_names:
  364.  
  365.             if done.has_key(product_name): continue
  366.             done[product_name]=1
  367.  
  368.             package_dir=path_join(product_dir, product_name)
  369.             if not isdir(package_dir): continue
  370.             if not exists(path_join(package_dir, '__init__.py')):
  371.                 if not exists(path_join(package_dir, '__init__.pyc')):
  372.                     continue
  373.  
  374.             pname="Products.%s" % product_name
  375.             try:
  376.                 product=__import__(pname, global_dict, global_dict, silly)
  377.                 if hasattr(product, '__module_aliases__'):
  378.                     for k, v in product.__module_aliases__:
  379.                         if not have_module(k):
  380.                             if type(v) is _st and have_module(v): v=modules[v]
  381.                             modules[k]=v
  382.             except:
  383.                 LOG('Zope',ERROR,'Couldn\'t import %s' % pname,
  384.                     error=sys.exc_info())
  385.                 f=StringIO()
  386.                 traceback.print_exc(100,f)
  387.                 f=f.getvalue()
  388.                 try: modules[pname].__import_error__=f
  389.                 except: pass
  390.  
  391.  
  392. def install_products(app):
  393.     # Install a list of products into the basic folder class, so
  394.     # that all folders know about top-level objects, aka products
  395.  
  396.     path_join=os.path.join
  397.     isdir=os.path.isdir
  398.     exists=os.path.exists
  399.     DictType=type({})
  400.  
  401.     from Folder import Folder
  402.     folder_permissions={}
  403.     for p in Folder.__ac_permissions__:
  404.         permission, names = p[:2]
  405.         folder_permissions[permission]=names
  406.  
  407.     meta_types=[]
  408.  
  409.     global_dict=globals()
  410.     silly=('__doc__',)
  411.  
  412.     done={}
  413.  
  414.     get_transaction().note('Prior to product installs')
  415.     get_transaction().commit()
  416.  
  417.     for product_dir in Products.__path__:
  418.  
  419.         product_names=os.listdir(product_dir)
  420.         product_names.sort()
  421.  
  422.         for product_name in product_names:
  423.             # For each product, we will import it and try to call the
  424.             # intialize() method in the product __init__ module. If
  425.             # the method doesnt exist, we put the old-style information
  426.             # together and do a default initialization.
  427.             if done.has_key(product_name):
  428.                 continue
  429.             done[product_name]=1
  430.  
  431.             package_dir=path_join(product_dir, product_name)
  432.             __traceback_info__=product_name
  433.             if not isdir(package_dir): continue
  434.             if not exists(path_join(package_dir, '__init__.py')):
  435.                 if not exists(path_join(package_dir, '__init__.pyc')):
  436.                     continue
  437.             try:
  438.                 product=__import__("Products.%s" % product_name,
  439.                                    global_dict, global_dict, silly)
  440.  
  441.                 # Install items into the misc_ namespace, used by products
  442.                 # and the framework itself to store common static resources
  443.                 # like icon images.
  444.                 misc_=pgetattr(product, 'misc_', {})
  445.                 if misc_:
  446.                     if type(misc_) is DictType:
  447.                         misc_=Misc_(product_name, misc_)
  448.                     Application.misc_.__dict__[product_name]=misc_
  449.  
  450.                 # Here we create a ProductContext object which contains
  451.                 # information about the product and provides an interface
  452.                 # for registering things like classes and help topics that
  453.                 # should be associated with that product. Products are
  454.                 # expected to implement a method named 'initialize' in
  455.                 # their __init__.py that takes the ProductContext as an
  456.                 # argument. 
  457.                 productObject=App.Product.initializeProduct(
  458.                     product, product_name, package_dir, app)
  459.                 context=ProductContext(productObject, app, product)
  460.  
  461.                 # Look for an 'initialize' method in the product. If it does
  462.                 # not exist, then this is an old product that has never been
  463.                 # updated. In that case, we will analyze the product and
  464.                 # build up enough information to do initialization manually.
  465.                 initmethod=pgetattr(product, 'initialize', None)
  466.                 if initmethod is not None:
  467.                     initmethod(context)                    
  468.  
  469.                 # Support old-style product metadata. Older products may
  470.                 # define attributes to name their permissions, meta_types,
  471.                 # constructors, etc.
  472.                 permissions={}
  473.                 new_permissions={}
  474.                 for p in pgetattr(product, '__ac_permissions__', ()):
  475.                     permission, names, default = (
  476.                         tuple(p)+('Manager',))[:3]
  477.                     if names:
  478.                         for name in names:
  479.                             permissions[name]=permission
  480.                     elif not folder_permissions.has_key(permission):
  481.                         new_permissions[permission]=()
  482.  
  483.                 for meta_type in pgetattr(product, 'meta_types', ()):
  484.                     # Modern product initialization via a ProductContext
  485.                     # adds 'product' and 'permission' keys to the meta_type
  486.                     # mapping. We have to add these here for old products.
  487.                     pname=permissions.get(meta_type['action'], None)
  488.                     if pname is not None:
  489.                         meta_type['permission']=pname
  490.                     meta_type['product']=productObject.id
  491.                     meta_types.append(meta_type)
  492.  
  493.                 for name,method in pgetattr(
  494.                     product, 'methods', {}).items():
  495.                     if not hasattr(Folder, name):
  496.                         setattr(Folder, name, method)
  497.                         if name[-9:]!='__roles__': # not Just setting roles
  498.                             if (permissions.has_key(name) and
  499.                                 not folder_permissions.has_key(
  500.                                     permissions[name])):
  501.                                 permission=permissions[name]
  502.                                 if new_permissions.has_key(permission):
  503.                                     new_permissions[permission].append(name)
  504.                                 else:
  505.                                     new_permissions[permission]=[name]
  506.  
  507.                 if new_permissions:
  508.                     new_permissions=new_permissions.items()
  509.                     for permission, names in new_permissions:
  510.                         folder_permissions[permission]=names
  511.                     new_permissions.sort()
  512.                     Folder.__dict__['__ac_permissions__']=tuple(
  513.                         list(Folder.__ac_permissions__)+new_permissions)
  514.  
  515.                 if os.environ.get('ZEO_CLIENT',''):
  516.                     # we don't want to install products from clients!
  517.                     get_transaction().abort()
  518.                 else:
  519.                     get_transaction().note('Installed product '+product_name)
  520.                     get_transaction().commit()
  521.  
  522.             except:
  523.                 LOG('Zope',ERROR,'Couldn\'t install %s' % product_name,
  524.                     error=sys.exc_info())
  525.                 get_transaction().abort()
  526.  
  527.     Products.meta_types=Products.meta_types+tuple(meta_types)
  528.  
  529.     Globals.default__class_init__(Folder)
  530.  
  531.  
  532. def pgetattr(product, name, default=install_products, __init__=0):
  533.     if not __init__ and hasattr(product, name): return getattr(product, name)
  534.     if hasattr(product, '__init__'):
  535.         product=product.__init__
  536.         if hasattr(product, name): return getattr(product, name)
  537.  
  538.     if default is not install_products: return default
  539.  
  540.     raise AttributeError, name
  541.